<!doctype html><html><head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><meta name=robots content="noodp"><meta http-equiv=x-ua-compatible content="IE=edge, chrome=1"><title>JavaMail-发送一封简单邮件（附带附件） - Yulin Lewis' Blog</title><meta name=keywords content="雨临Lewis,Java,hugo,hexo,博客"><meta name=Description content="不想当写手的码农不是好咸鱼_(xз」∠)_"><meta property="og:title" content="JavaMail-发送一封简单邮件（附带附件）"><meta property="og:description" content="代码实现
最近使用到JavaMail，写了个简单的工具类，记录一下。


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161


import java.util.Date;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;

public class JavaMailUtils {
	//连接SMTP服务器的主机名，这里以qq邮箱为例
    private static final String SMTP_HOST = &#34;smtp.qq.com&#34;;
    //连接的端口号，587为ssl端口，默认为25端口
    private static final String SMTP_PORT = &#34;587&#34;;
    //发件人
    private static final String MAIL_FROM = &#34;XXX@qq.com&#34;;
    //连接邮件服务器的用户名（邮箱地址去除了@qq.com的部分）
    private static final String USER = &#34;XXX&#34;;
    /**
     * 授权码，就是你在邮件服务器上注册的密码，不是你的qq密码
     * 在邮箱里开启smtp/imap服务时需要发送短信，成功后会得到一个授权码
     */
    private static final String PASSWORD = &#34;授权码&#34;;

    private JavaMailUtils() {
    }

    /**
     * send mail without attachments
     *
     * @param mailTo
     * @param mailCc
     * @param subject
     * @param content
     * @throws AddressException
     * @throws MessagingException
     */
    public static void sendMail(final String mailTo, final String mailCc, final String subject, final String content)
            throws Exception {
        // get the session
        final Session session = getSession();
        // create a mail
        final MimeMessage message = createMail(session, mailTo, mailCc, subject, content);
        // get the transport
        final Transport transport = session.getTransport();
        transport.connect(USER, PASSWORD);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    public static void sendMail(final String mailTo, final String mailCc, final String subject, final String content,
            final String[] attachments) throws Exception {
        // get the session
        final Session session = getSession();
        // create a mail
        final MimeMessage message = createMail(session, mailTo, mailCc, subject, content, attachments);
        // get the transport
        final Transport transport = session.getTransport();
        transport.connect(USER, PASSWORD);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    /**
     * create a mail without attachments
     *
     * @param session
     * @param mailTo
     * @param mailCc
     * @param subject
     * @param content
     * @return
     * @throws Exception
     */
    private static MimeMessage createMail(final Session session, final String mailTo, final String mailCc,
            final String subject, final String content) throws Exception {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(MAIL_FROM));
        message.setRecipients(RecipientType.TO, InternetAddress.parse(mailTo));
        message.setRecipients(RecipientType.CC, InternetAddress.parse(mailCc));
        message.setSubject(subject);
        message.setContent(content, &#34;text/html;charset=UTF-8&#34;);
        message.setSentDate(new Date());
        message.saveChanges();

        return message;
    }

    /**
     * create a mail with attachments
     *
     * @param session
     * @param mailTo
     * @param mailCc
     * @param subject
     * @param content
     * @param attachments
     * @return
     */
    private static MimeMessage createMail(final Session session, final String mailTo, final String mailCc,
            final String subject, final String content, final String[] attachments) throws Exception {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(MAIL_FROM));
        message.setRecipients(RecipientType.TO, InternetAddress.parse(mailTo));
        message.setRecipients(RecipientType.CC, InternetAddress.parse(mailCc));
        message.setSubject(subject);
        // set the multipart of the mail
        final MimeMultipart multipart = new MimeMultipart();
        // set content part of the mail
        final MimeBodyPart contentPart = new MimeBodyPart();
        contentPart.setContent(content, &#34;text/html;charset=UTF-8&#34;);
        multipart.addBodyPart(contentPart);
        // set attachment part of the mail
        final MimeBodyPart attach1 = new MimeBodyPart();
        final MimeBodyPart attach2 = new MimeBodyPart();
        if (attachments != null && attachments.length != 0) {
            final int length = attachments.length;
            if (length == 1) {
                attach1.attachFile(attachments[0]);
                multipart.addBodyPart(attach1);
            }
            if (length == 2) {
                attach1.attachFile(attachments[0]);
                attach2.attachFile(attachments[1]);
                multipart.addBodyPart(attach1);
                multipart.addBodyPart(attach2);
            }
        }
        message.setContent(multipart);
        message.setSentDate(new Date());
        message.saveChanges();

        return message;
    }

    /**
     * get the session to transport mails
     */
    private static Session getSession() {
        // set the properties for connecting the mail server
        final Properties props = new Properties();
        props.setProperty(&#34;mail.debug&#34;, &#34;true&#34;);
        props.setProperty(&#34;mail.transport.protocol&#34;, &#34;smtp&#34;);
        props.setProperty(&#34;mail.host&#34;, SMTP_HOST);
        props.setProperty(&#34;mail.smtp.auth&#34;, &#34;true&#34;);
        props.setProperty(&#34;mail.smtp.port&#34;, SMTP_PORT);
        // ssl
        props.setProperty(&#34;mail.imap.ssl.enable&#34;, &#34;true&#34;);
        props.setProperty(&#34;mail.imap.ssl.socketFactory.class&#34;, &#34;DummySSLSocketFactory&#34;);
        props.setProperty(&#34;mail.imap.ssl.socketFactory.fallback&#34;, &#34;false&#34;);
        // create the session
        final Session session = Session.getDefaultInstance(props);

        return session;
    }

}"><meta property="og:type" content="article"><meta property="og:url" content="https://lewky.cn/posts/javamail.html/"><meta property="og:image" content="https://lewky.cn/logo.png"><meta property="article:published_time" content="2017-11-22T23:31:05+08:00"><meta property="article:modified_time" content="2021-03-17T23:31:05+08:00"><meta name=twitter:card content="summary_large_image"><meta name=twitter:image content="https://lewky.cn/logo.png"><meta name=twitter:title content="JavaMail-发送一封简单邮件（附带附件）"><meta name=twitter:description content="代码实现
最近使用到JavaMail，写了个简单的工具类，记录一下。


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161


import java.util.Date;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;

public class JavaMailUtils {
	//连接SMTP服务器的主机名，这里以qq邮箱为例
    private static final String SMTP_HOST = &#34;smtp.qq.com&#34;;
    //连接的端口号，587为ssl端口，默认为25端口
    private static final String SMTP_PORT = &#34;587&#34;;
    //发件人
    private static final String MAIL_FROM = &#34;XXX@qq.com&#34;;
    //连接邮件服务器的用户名（邮箱地址去除了@qq.com的部分）
    private static final String USER = &#34;XXX&#34;;
    /**
     * 授权码，就是你在邮件服务器上注册的密码，不是你的qq密码
     * 在邮箱里开启smtp/imap服务时需要发送短信，成功后会得到一个授权码
     */
    private static final String PASSWORD = &#34;授权码&#34;;

    private JavaMailUtils() {
    }

    /**
     * send mail without attachments
     *
     * @param mailTo
     * @param mailCc
     * @param subject
     * @param content
     * @throws AddressException
     * @throws MessagingException
     */
    public static void sendMail(final String mailTo, final String mailCc, final String subject, final String content)
            throws Exception {
        // get the session
        final Session session = getSession();
        // create a mail
        final MimeMessage message = createMail(session, mailTo, mailCc, subject, content);
        // get the transport
        final Transport transport = session.getTransport();
        transport.connect(USER, PASSWORD);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    public static void sendMail(final String mailTo, final String mailCc, final String subject, final String content,
            final String[] attachments) throws Exception {
        // get the session
        final Session session = getSession();
        // create a mail
        final MimeMessage message = createMail(session, mailTo, mailCc, subject, content, attachments);
        // get the transport
        final Transport transport = session.getTransport();
        transport.connect(USER, PASSWORD);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }

    /**
     * create a mail without attachments
     *
     * @param session
     * @param mailTo
     * @param mailCc
     * @param subject
     * @param content
     * @return
     * @throws Exception
     */
    private static MimeMessage createMail(final Session session, final String mailTo, final String mailCc,
            final String subject, final String content) throws Exception {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(MAIL_FROM));
        message.setRecipients(RecipientType.TO, InternetAddress.parse(mailTo));
        message.setRecipients(RecipientType.CC, InternetAddress.parse(mailCc));
        message.setSubject(subject);
        message.setContent(content, &#34;text/html;charset=UTF-8&#34;);
        message.setSentDate(new Date());
        message.saveChanges();

        return message;
    }

    /**
     * create a mail with attachments
     *
     * @param session
     * @param mailTo
     * @param mailCc
     * @param subject
     * @param content
     * @param attachments
     * @return
     */
    private static MimeMessage createMail(final Session session, final String mailTo, final String mailCc,
            final String subject, final String content, final String[] attachments) throws Exception {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(MAIL_FROM));
        message.setRecipients(RecipientType.TO, InternetAddress.parse(mailTo));
        message.setRecipients(RecipientType.CC, InternetAddress.parse(mailCc));
        message.setSubject(subject);
        // set the multipart of the mail
        final MimeMultipart multipart = new MimeMultipart();
        // set content part of the mail
        final MimeBodyPart contentPart = new MimeBodyPart();
        contentPart.setContent(content, &#34;text/html;charset=UTF-8&#34;);
        multipart.addBodyPart(contentPart);
        // set attachment part of the mail
        final MimeBodyPart attach1 = new MimeBodyPart();
        final MimeBodyPart attach2 = new MimeBodyPart();
        if (attachments != null && attachments.length != 0) {
            final int length = attachments.length;
            if (length == 1) {
                attach1.attachFile(attachments[0]);
                multipart.addBodyPart(attach1);
            }
            if (length == 2) {
                attach1.attachFile(attachments[0]);
                attach2.attachFile(attachments[1]);
                multipart.addBodyPart(attach1);
                multipart.addBodyPart(attach2);
            }
        }
        message.setContent(multipart);
        message.setSentDate(new Date());
        message.saveChanges();

        return message;
    }

    /**
     * get the session to transport mails
     */
    private static Session getSession() {
        // set the properties for connecting the mail server
        final Properties props = new Properties();
        props.setProperty(&#34;mail.debug&#34;, &#34;true&#34;);
        props.setProperty(&#34;mail.transport.protocol&#34;, &#34;smtp&#34;);
        props.setProperty(&#34;mail.host&#34;, SMTP_HOST);
        props.setProperty(&#34;mail.smtp.auth&#34;, &#34;true&#34;);
        props.setProperty(&#34;mail.smtp.port&#34;, SMTP_PORT);
        // ssl
        props.setProperty(&#34;mail.imap.ssl.enable&#34;, &#34;true&#34;);
        props.setProperty(&#34;mail.imap.ssl.socketFactory.class&#34;, &#34;DummySSLSocketFactory&#34;);
        props.setProperty(&#34;mail.imap.ssl.socketFactory.fallback&#34;, &#34;false&#34;);
        // create the session
        final Session session = Session.getDefaultInstance(props);

        return session;
    }

}"><meta name=application-name content="雨临Lewis的博客"><meta name=apple-mobile-web-app-title content="雨临Lewis的博客"><meta name=theme-color content="#ffffff"><meta name=msapplication-TileColor content="#da532c"><link rel="shortcut icon" type=image/x-icon href=/favicon.ico><link rel=icon type=image/png sizes=32x32 href=/favicon-32x32.png><link rel=icon type=image/png sizes=16x16 href=/favicon-16x16.png><link rel=apple-touch-icon sizes=180x180 href=/apple-touch-icon.png><link rel=mask-icon href=/safari-pinned-tab.svg color=#5bbad5><link rel=manifest href=/site.webmanifest><link rel=canonical href=https://lewky.cn/posts/javamail.html/><link rel=prev href=https://lewky.cn/posts/39f5b6b2.html/><link rel=next href=https://lewky.cn/posts/90196397.html/><link rel=stylesheet href=https://cdn.jsdelivr.net/npm/normalize.css@8.0.1/normalize.min.css><link rel=stylesheet href=/css/style.min.css><link rel=stylesheet href=https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.13.0/css/all.min.css><link rel=stylesheet href=https://cdn.jsdelivr.net/npm/animate.css@3.7.2/animate.min.css><script type=application/ld+json>{"@context":"http://schema.org","@type":"BlogPosting","headline":"JavaMail-发送一封简单邮件（附带附件）","inLanguage":"","mainEntityOfPage":{"@type":"WebPage","@id":"https:\/\/lewky.cn\/posts\/javamail.html\/"},"genre":"posts","keywords":"工作记录","wordcount":1469,"url":"https:\/\/lewky.cn\/posts\/javamail.html\/","datePublished":"2017-11-22T23:31:05+08:00","dateModified":"2021-03-17T23:31:05+08:00","license":"This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.","publisher":{"@type":"Organization","name":"雨临Lewis","logo":"https:\/\/lewky.cn\/images\/avatar.jpg"},"author":{"@type":"Person","name":"雨临Lewis"},"description":""}</script></head><body header-desktop=fixed header-mobile=auto><script type=text/javascript>(window.localStorage&&localStorage.getItem('theme')?localStorage.getItem('theme')==='dark':('auto'==='auto'?window.matchMedia('(prefers-color-scheme: dark)').matches:'auto'==='dark'))&&document.body.setAttribute('theme','dark');</script><div id=mask></div><div class=wrapper><header class=desktop id=header-desktop><div class=header-wrapper><a href=https://github.com/lewky class=github-corner target=_blank title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="3.5rem" height="3.5rem" viewBox="0 0 250 250" style="fill:#70b7fd;color:#fff;position:absolute;top:0;border:0;left:0;transform:scale(-1,1)" aria-hidden="true"><path d="M0 0 115 115h15l12 27L250 250V0z"/><path d="M128.3 109C113.8 99.7 119 89.6 119 89.6 122 82.7 120.5 78.6 120.5 78.6 119.2 72 123.4 76.3 123.4 76.3 127.3 80.9 125.5 87.3 125.5 87.3 122.9 97.6 130.6 101.9 134.4 103.2" fill="currentcolor" style="transform-origin:130px 106px" class="octo-arm"/><path d="M115 115C114.9 115.1 118.7 116.5 119.8 115.4L133.7 101.6C136.9 99.2 139.9 98.4 142.2 98.6 133.8 88 127.5 74.4 143.8 58 148.5 53.4 154 51.2 159.7 51 160.3 49.4 163.2 43.6 171.4 40.1 171.4 40.1 176.1 42.5 178.8 56.2 183.1 58.6 187.2 61.8 190.9 65.4 194.5 69 197.7 73.2 200.1 77.6 213.8 80.2 216.3 84.9 216.3 84.9 212.7 93.1 206.9 96 205.4 96.6 205.1 102.4 203 107.8 198.3 112.5 181.9 128.9 168.3 122.5 157.7 114.1 157.9 116.9 156.7 120.9 152.7 124.9L141 136.5C139.8 137.7 141.6 141.9 141.8 141.8z" fill="currentcolor" class="octo-body"/></svg></a><div class=header-title><a href=/ title="Yulin Lewis' Blog"><span class=header-title-pre><i class="fas fa-fw fa-atom"></i></span>雨临Lewis</a></div><div class=menu><div class=menu-inner><div class=dropdown><a href=/posts/ class="menu-item menu-more dropbtn" title=点击查看所有文章><i class="fas fa-fw fa-archive"></i>归档</a><div class="menu-more-content dropdown-content"><a href=/categories/><i class="fas fa-fw fa-th"></i>分类 </a><a href=/tags/><i class="fas fa-fw fa-tag"></i>标签 </a><a href=/hot/ title=文章热度Top15><i class="fas fa-fw fa-fire"></i>热度 </a><a href=/donation/ title=感谢打赏，老板大气~><i class="fas fa-fw fa-donate"></i>打赏 </a><a href=/about/><i class="fas fa-fw fa-at"></i>关于</a></div></div><a class=menu-item href=/friends/ title=欢迎申请友链><i class="fas fa-fw fa-link"></i>友链</a><div class=dropdown><a href=javascript:void(0); class="menu-item menu-more dropbtn" title=一些有意思的东东~><i class="fas fa-fw fa-fan fa-spin"></i>趣味</a><div class="menu-more-content dropdown-content"><a href=/funny/high/ title="前方高能♂ 小心外放！" target=_blank rel=noopener><i class="fas fa-fw fa-dizzy"></i>燥起来！ </a><a href=/funny/mikutap/ title=初音未来音乐游戏 target=_blank rel=noopener><i class="fas fa-fw fa-music"></i>在线打碟 </a><a href=/funny/catch-the-cat/ title=逮住那只猫!><i class="fas fa-fw fa-cat"></i>抓住猫咪</a></div></div><div class=dropdown><a href=/ class="menu-item menu-more dropbtn" title=回到首页><i class="fas fa-fw fa-atom"></i>站点</a><div class="menu-more-content dropdown-content"><a href=/bbs/ title=来留言吧~><i class="fas fa-fw fa-comment"></i>公告留言 </a><a href=https://seo.chinaz.com target=_blank rel=noopener><i class="fas fa-fw fa-chart-line"></i>SEO查询 </a><a href=https://www.ping.cn/http/lewky.cn target=_blank rel=noopener><i class="fas fa-fw fa-bezier-curve"></i>网站测速 </a><a href=/posts/e62c38c4.html/><i class="fas fa-fw fa-cog fa-spin"></i>建站日志</a></div></div><div class=dropdown><a href=javascript:void(0); class="menu-item menu-more dropbtn"><i class="fas fa-fw fa-book"></i>文档</a><div class="menu-more-content dropdown-content"><a href=https://gohugo.io/documentation/ target=_blank rel=noopener><i class="fas fa-fw fa-star"></i>Hugo文档 </a><a href=https://javanote.doc.lewky.cn/ title=尚在完善中~ target=_blank rel=noopener><i class="fab fa-fw fa-java"></i>Java 笔记</a></div></div><a class=menu-item href=/search/ title=渲染搜索结果需要等待几秒钟~><i class="fas fa-fw fa-search"></i>搜索
</a><span class="menu-item delimiter"></span><a href=https://travellings.link target=_blank class=menu-item rel=noopener title=开往-友链接力><i class="fas fa-fw fa-subway"></i></a><a href=https://rssblog.vercel.app/ class=menu-item target=_blank rel=noopener title=RSSBlog><i class="fas fa-fw fa-inbox"></i></a><a href=https://github.com/lewky class=menu-item target=_blank rel=noopener title=GitHub><i class="fab fa-fw fa-github"></i></a></div></div></div></header><header class=mobile id=header-mobile><div class=header-container><div class=header-wrapper><div class=header-title><a href=/ title="Yulin Lewis' Blog"><span class=header-title-pre><i class="fas fa-fw fa-atom"></i></span>雨临Lewis</a></div><div class=menu-toggle id=menu-toggle-mobile><span></span><span></span><span></span></div></div><div class=menu id=menu-mobile><div class=dropdown><a href=/posts/ class="menu-item menu-more dropbtn" title=点击查看所有文章><i class="fas fa-fw fa-archive"></i>归档</a><div class="menu-more-content dropdown-content"><a href=/categories/><i class="fas fa-fw fa-th"></i>分类 </a><a href=/tags/><i class="fas fa-fw fa-tag"></i>标签 </a><a href=/hot/ title=文章热度Top15><i class="fas fa-fw fa-fire"></i>热度 </a><a href=/donation/ title=感谢打赏，老板大气~><i class="fas fa-fw fa-donate"></i>打赏 </a><a href=/about/><i class="fas fa-fw fa-at"></i>关于</a></div></div><a class=menu-item href=/friends/ title=欢迎申请友链><i class="fas fa-fw fa-link"></i>友链</a><div class=dropdown><a href=javascript:void(0); class="menu-item menu-more dropbtn" title=一些有意思的东东~><i class="fas fa-fw fa-fan fa-spin"></i>趣味</a><div class="menu-more-content dropdown-content"><a href=/funny/high/ title="前方高能♂ 小心外放！" target=_blank rel=noopener><i class="fas fa-fw fa-dizzy"></i>燥起来！ </a><a href=/funny/mikutap/ title=初音未来音乐游戏 target=_blank rel=noopener><i class="fas fa-fw fa-music"></i>在线打碟 </a><a href=/funny/catch-the-cat/ title=逮住那只猫!><i class="fas fa-fw fa-cat"></i>抓住猫咪</a></div></div><div class=dropdown><a href=/ class="menu-item menu-more dropbtn" title=回到首页><i class="fas fa-fw fa-atom"></i>站点</a><div class="menu-more-content dropdown-content"><a href=/bbs/ title=来留言吧~><i class="fas fa-fw fa-comment"></i>公告留言 </a><a href=https://seo.chinaz.com target=_blank rel=noopener><i class="fas fa-fw fa-chart-line"></i>SEO查询 </a><a href=https://www.ping.cn/http/lewky.cn target=_blank rel=noopener><i class="fas fa-fw fa-bezier-curve"></i>网站测速 </a><a href=/posts/e62c38c4.html/><i class="fas fa-fw fa-cog fa-spin"></i>建站日志</a></div></div><div class=dropdown><a href=javascript:void(0); class="menu-item menu-more dropbtn"><i class="fas fa-fw fa-book"></i>文档</a><div class="menu-more-content dropdown-content"><a href=https://gohugo.io/documentation/ target=_blank rel=noopener><i class="fas fa-fw fa-star"></i>Hugo文档 </a><a href=https://javanote.doc.lewky.cn/ title=尚在完善中~ target=_blank rel=noopener><i class="fab fa-fw fa-java"></i>Java 笔记</a></div></div><a class=menu-item href=/search/ title=渲染搜索结果需要等待几秒钟~><i class="fas fa-fw fa-search"></i>搜索</a>
<a href=https://travellings.link target=_blank class=menu-item rel=noopener title=开往-友链接力><i class="fas fa-fw fa-subway"></i></a><a href=https://rssblog.vercel.app/ class=menu-item target=_blank rel=noopener title=RSSBlog><i class="fas fa-fw fa-inbox"></i></a><a href=https://github.com/lewky class=menu-item target=_blank rel=noopener title=GitHub><i class="fab fa-fw fa-github"></i></a></div></div></header><div class="search-dropdown desktop"><div id=search-dropdown-desktop></div></div><div class="search-dropdown mobile"><div id=search-dropdown-mobile></div></div><main class=main><div class=container><div class=toc id=toc-auto><h2 class=toc-title>目录</h2><div class=toc-content id=toc-content-auto></div></div><article class="page single"><h1 class="single-title animated flipInX">JavaMail-发送一封简单邮件（附带附件）</h1><div class=post-meta><div class=post-meta-line><span class=post-author><a href=/ title=Author rel=author class=author><i class="fas fa-user-circle fa-fw"></i>雨临Lewis</a></span>&nbsp;<span class=post-category>收录于 <a href=/categories/%E5%B7%A5%E4%BD%9C%E8%AE%B0%E5%BD%95/><i class="far fa-folder fa-fw"></i>工作记录</a></span></div><div class=post-meta-line><i class="far fa-calendar fa-fw"></i>&nbsp;<time datetime=2017-11-22>2017-11-22</time>&nbsp;<i class="far fa-calendar-plus fa-fw"></i>&nbsp;<time datetime=2021-03-17>2021-03-17</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 1469 字
<i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 3 分钟&nbsp;<span id=/posts/javamail.html/ class=leancloud_visitors data-flag-title=JavaMail-发送一封简单邮件（附带附件）>
<i class="far fa-eye fa-fw"></i>&nbsp;<span class=leancloud-visitors-count></span>&nbsp;次阅读
</span>&nbsp;
<a href=#comments id=post-meta-vcount title=查看评论><i class="fas fa-comment fa-fw"></i>&nbsp;<span id=/posts/javamail.html/ class=waline-comment-count></span>&nbsp;条评论</a></div></div><div class="details toc" id=toc-static kept><div class="details-summary toc-title"><span>目录</span>
<span><i class="details-icon fas fa-angle-right"></i></span></div><div class="details-content toc-content" id=toc-content-static><nav id=TableOfContents><ol><li><a href=#代码实现>代码实现</a></li><li><a href=#补充>补充</a></li><li><a href=#参考链接>参考链接</a></li></ol></nav></div></div><div class=content id=content><h2 id=代码实现>代码实现</h2><p>最近使用到JavaMail，写了个简单的工具类，记录一下。</p><div class=highlight><div class=chroma><table class=lntable><tr><td class=lntd><pre class=chroma><code><span class=lnt>  1
</span><span class=lnt>  2
</span><span class=lnt>  3
</span><span class=lnt>  4
</span><span class=lnt>  5
</span><span class=lnt>  6
</span><span class=lnt>  7
</span><span class=lnt>  8
</span><span class=lnt>  9
</span><span class=lnt> 10
</span><span class=lnt> 11
</span><span class=lnt> 12
</span><span class=lnt> 13
</span><span class=lnt> 14
</span><span class=lnt> 15
</span><span class=lnt> 16
</span><span class=lnt> 17
</span><span class=lnt> 18
</span><span class=lnt> 19
</span><span class=lnt> 20
</span><span class=lnt> 21
</span><span class=lnt> 22
</span><span class=lnt> 23
</span><span class=lnt> 24
</span><span class=lnt> 25
</span><span class=lnt> 26
</span><span class=lnt> 27
</span><span class=lnt> 28
</span><span class=lnt> 29
</span><span class=lnt> 30
</span><span class=lnt> 31
</span><span class=lnt> 32
</span><span class=lnt> 33
</span><span class=lnt> 34
</span><span class=lnt> 35
</span><span class=lnt> 36
</span><span class=lnt> 37
</span><span class=lnt> 38
</span><span class=lnt> 39
</span><span class=lnt> 40
</span><span class=lnt> 41
</span><span class=lnt> 42
</span><span class=lnt> 43
</span><span class=lnt> 44
</span><span class=lnt> 45
</span><span class=lnt> 46
</span><span class=lnt> 47
</span><span class=lnt> 48
</span><span class=lnt> 49
</span><span class=lnt> 50
</span><span class=lnt> 51
</span><span class=lnt> 52
</span><span class=lnt> 53
</span><span class=lnt> 54
</span><span class=lnt> 55
</span><span class=lnt> 56
</span><span class=lnt> 57
</span><span class=lnt> 58
</span><span class=lnt> 59
</span><span class=lnt> 60
</span><span class=lnt> 61
</span><span class=lnt> 62
</span><span class=lnt> 63
</span><span class=lnt> 64
</span><span class=lnt> 65
</span><span class=lnt> 66
</span><span class=lnt> 67
</span><span class=lnt> 68
</span><span class=lnt> 69
</span><span class=lnt> 70
</span><span class=lnt> 71
</span><span class=lnt> 72
</span><span class=lnt> 73
</span><span class=lnt> 74
</span><span class=lnt> 75
</span><span class=lnt> 76
</span><span class=lnt> 77
</span><span class=lnt> 78
</span><span class=lnt> 79
</span><span class=lnt> 80
</span><span class=lnt> 81
</span><span class=lnt> 82
</span><span class=lnt> 83
</span><span class=lnt> 84
</span><span class=lnt> 85
</span><span class=lnt> 86
</span><span class=lnt> 87
</span><span class=lnt> 88
</span><span class=lnt> 89
</span><span class=lnt> 90
</span><span class=lnt> 91
</span><span class=lnt> 92
</span><span class=lnt> 93
</span><span class=lnt> 94
</span><span class=lnt> 95
</span><span class=lnt> 96
</span><span class=lnt> 97
</span><span class=lnt> 98
</span><span class=lnt> 99
</span><span class=lnt>100
</span><span class=lnt>101
</span><span class=lnt>102
</span><span class=lnt>103
</span><span class=lnt>104
</span><span class=lnt>105
</span><span class=lnt>106
</span><span class=lnt>107
</span><span class=lnt>108
</span><span class=lnt>109
</span><span class=lnt>110
</span><span class=lnt>111
</span><span class=lnt>112
</span><span class=lnt>113
</span><span class=lnt>114
</span><span class=lnt>115
</span><span class=lnt>116
</span><span class=lnt>117
</span><span class=lnt>118
</span><span class=lnt>119
</span><span class=lnt>120
</span><span class=lnt>121
</span><span class=lnt>122
</span><span class=lnt>123
</span><span class=lnt>124
</span><span class=lnt>125
</span><span class=lnt>126
</span><span class=lnt>127
</span><span class=lnt>128
</span><span class=lnt>129
</span><span class=lnt>130
</span><span class=lnt>131
</span><span class=lnt>132
</span><span class=lnt>133
</span><span class=lnt>134
</span><span class=lnt>135
</span><span class=lnt>136
</span><span class=lnt>137
</span><span class=lnt>138
</span><span class=lnt>139
</span><span class=lnt>140
</span><span class=lnt>141
</span><span class=lnt>142
</span><span class=lnt>143
</span><span class=lnt>144
</span><span class=lnt>145
</span><span class=lnt>146
</span><span class=lnt>147
</span><span class=lnt>148
</span><span class=lnt>149
</span><span class=lnt>150
</span><span class=lnt>151
</span><span class=lnt>152
</span><span class=lnt>153
</span><span class=lnt>154
</span><span class=lnt>155
</span><span class=lnt>156
</span><span class=lnt>157
</span><span class=lnt>158
</span><span class=lnt>159
</span><span class=lnt>160
</span><span class=lnt>161
</span></code></pre></td><td class=lntd><pre class=chroma><code class=language-java data-lang=java><span class=kn>import</span> <span class=nn>java.util.Date</span><span class=o>;</span>
<span class=kn>import</span> <span class=nn>java.util.Properties</span><span class=o>;</span>

<span class=kn>import</span> <span class=nn>javax.mail.MessagingException</span><span class=o>;</span>
<span class=kn>import</span> <span class=nn>javax.mail.Session</span><span class=o>;</span>
<span class=kn>import</span> <span class=nn>javax.mail.Transport</span><span class=o>;</span>
<span class=kn>import</span> <span class=nn>javax.mail.internet.AddressException</span><span class=o>;</span>
<span class=kn>import</span> <span class=nn>javax.mail.internet.InternetAddress</span><span class=o>;</span>
<span class=kn>import</span> <span class=nn>javax.mail.internet.MimeBodyPart</span><span class=o>;</span>
<span class=kn>import</span> <span class=nn>javax.mail.internet.MimeMessage</span><span class=o>;</span>
<span class=kn>import</span> <span class=nn>javax.mail.internet.MimeMessage.RecipientType</span><span class=o>;</span>
<span class=kn>import</span> <span class=nn>javax.mail.internet.MimeMultipart</span><span class=o>;</span>

<span class=kd>public</span> <span class=kd>class</span> <span class=nc>JavaMailUtils</span> <span class=o>{</span>
	<span class=c1>//连接SMTP服务器的主机名，这里以qq邮箱为例
</span><span class=c1></span>    <span class=kd>private</span> <span class=kd>static</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>SMTP_HOST</span> <span class=o>=</span> <span class=s>&#34;smtp.qq.com&#34;</span><span class=o>;</span>
    <span class=c1>//连接的端口号，587为ssl端口，默认为25端口
</span><span class=c1></span>    <span class=kd>private</span> <span class=kd>static</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>SMTP_PORT</span> <span class=o>=</span> <span class=s>&#34;587&#34;</span><span class=o>;</span>
    <span class=c1>//发件人
</span><span class=c1></span>    <span class=kd>private</span> <span class=kd>static</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>MAIL_FROM</span> <span class=o>=</span> <span class=s>&#34;XXX@qq.com&#34;</span><span class=o>;</span>
    <span class=c1>//连接邮件服务器的用户名（邮箱地址去除了@qq.com的部分）
</span><span class=c1></span>    <span class=kd>private</span> <span class=kd>static</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>USER</span> <span class=o>=</span> <span class=s>&#34;XXX&#34;</span><span class=o>;</span>
    <span class=cm>/**
</span><span class=cm>     * 授权码，就是你在邮件服务器上注册的密码，不是你的qq密码
</span><span class=cm>     * 在邮箱里开启smtp/imap服务时需要发送短信，成功后会得到一个授权码
</span><span class=cm>     */</span>
    <span class=kd>private</span> <span class=kd>static</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>PASSWORD</span> <span class=o>=</span> <span class=s>&#34;授权码&#34;</span><span class=o>;</span>

    <span class=kd>private</span> <span class=nf>JavaMailUtils</span><span class=o>()</span> <span class=o>{</span>
    <span class=o>}</span>

    <span class=cm>/**
</span><span class=cm>     * send mail without attachments
</span><span class=cm>     *
</span><span class=cm>     * @param mailTo
</span><span class=cm>     * @param mailCc
</span><span class=cm>     * @param subject
</span><span class=cm>     * @param content
</span><span class=cm>     * @throws AddressException
</span><span class=cm>     * @throws MessagingException
</span><span class=cm>     */</span>
    <span class=kd>public</span> <span class=kd>static</span> <span class=kt>void</span> <span class=nf>sendMail</span><span class=o>(</span><span class=kd>final</span> <span class=n>String</span> <span class=n>mailTo</span><span class=o>,</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>mailCc</span><span class=o>,</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>subject</span><span class=o>,</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>content</span><span class=o>)</span>
            <span class=kd>throws</span> <span class=n>Exception</span> <span class=o>{</span>
        <span class=c1>// get the session
</span><span class=c1></span>        <span class=kd>final</span> <span class=n>Session</span> <span class=n>session</span> <span class=o>=</span> <span class=n>getSession</span><span class=o>();</span>
        <span class=c1>// create a mail
</span><span class=c1></span>        <span class=kd>final</span> <span class=n>MimeMessage</span> <span class=n>message</span> <span class=o>=</span> <span class=n>createMail</span><span class=o>(</span><span class=n>session</span><span class=o>,</span> <span class=n>mailTo</span><span class=o>,</span> <span class=n>mailCc</span><span class=o>,</span> <span class=n>subject</span><span class=o>,</span> <span class=n>content</span><span class=o>);</span>
        <span class=c1>// get the transport
</span><span class=c1></span>        <span class=kd>final</span> <span class=n>Transport</span> <span class=n>transport</span> <span class=o>=</span> <span class=n>session</span><span class=o>.</span><span class=na>getTransport</span><span class=o>();</span>
        <span class=n>transport</span><span class=o>.</span><span class=na>connect</span><span class=o>(</span><span class=n>USER</span><span class=o>,</span> <span class=n>PASSWORD</span><span class=o>);</span>
        <span class=n>transport</span><span class=o>.</span><span class=na>sendMessage</span><span class=o>(</span><span class=n>message</span><span class=o>,</span> <span class=n>message</span><span class=o>.</span><span class=na>getAllRecipients</span><span class=o>());</span>
        <span class=n>transport</span><span class=o>.</span><span class=na>close</span><span class=o>();</span>
    <span class=o>}</span>

    <span class=kd>public</span> <span class=kd>static</span> <span class=kt>void</span> <span class=nf>sendMail</span><span class=o>(</span><span class=kd>final</span> <span class=n>String</span> <span class=n>mailTo</span><span class=o>,</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>mailCc</span><span class=o>,</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>subject</span><span class=o>,</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>content</span><span class=o>,</span>
            <span class=kd>final</span> <span class=n>String</span><span class=o>[]</span> <span class=n>attachments</span><span class=o>)</span> <span class=kd>throws</span> <span class=n>Exception</span> <span class=o>{</span>
        <span class=c1>// get the session
</span><span class=c1></span>        <span class=kd>final</span> <span class=n>Session</span> <span class=n>session</span> <span class=o>=</span> <span class=n>getSession</span><span class=o>();</span>
        <span class=c1>// create a mail
</span><span class=c1></span>        <span class=kd>final</span> <span class=n>MimeMessage</span> <span class=n>message</span> <span class=o>=</span> <span class=n>createMail</span><span class=o>(</span><span class=n>session</span><span class=o>,</span> <span class=n>mailTo</span><span class=o>,</span> <span class=n>mailCc</span><span class=o>,</span> <span class=n>subject</span><span class=o>,</span> <span class=n>content</span><span class=o>,</span> <span class=n>attachments</span><span class=o>);</span>
        <span class=c1>// get the transport
</span><span class=c1></span>        <span class=kd>final</span> <span class=n>Transport</span> <span class=n>transport</span> <span class=o>=</span> <span class=n>session</span><span class=o>.</span><span class=na>getTransport</span><span class=o>();</span>
        <span class=n>transport</span><span class=o>.</span><span class=na>connect</span><span class=o>(</span><span class=n>USER</span><span class=o>,</span> <span class=n>PASSWORD</span><span class=o>);</span>
        <span class=n>transport</span><span class=o>.</span><span class=na>sendMessage</span><span class=o>(</span><span class=n>message</span><span class=o>,</span> <span class=n>message</span><span class=o>.</span><span class=na>getAllRecipients</span><span class=o>());</span>
        <span class=n>transport</span><span class=o>.</span><span class=na>close</span><span class=o>();</span>
    <span class=o>}</span>

    <span class=cm>/**
</span><span class=cm>     * create a mail without attachments
</span><span class=cm>     *
</span><span class=cm>     * @param session
</span><span class=cm>     * @param mailTo
</span><span class=cm>     * @param mailCc
</span><span class=cm>     * @param subject
</span><span class=cm>     * @param content
</span><span class=cm>     * @return
</span><span class=cm>     * @throws Exception
</span><span class=cm>     */</span>
    <span class=kd>private</span> <span class=kd>static</span> <span class=n>MimeMessage</span> <span class=nf>createMail</span><span class=o>(</span><span class=kd>final</span> <span class=n>Session</span> <span class=n>session</span><span class=o>,</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>mailTo</span><span class=o>,</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>mailCc</span><span class=o>,</span>
            <span class=kd>final</span> <span class=n>String</span> <span class=n>subject</span><span class=o>,</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>content</span><span class=o>)</span> <span class=kd>throws</span> <span class=n>Exception</span> <span class=o>{</span>
        <span class=kd>final</span> <span class=n>MimeMessage</span> <span class=n>message</span> <span class=o>=</span> <span class=k>new</span> <span class=n>MimeMessage</span><span class=o>(</span><span class=n>session</span><span class=o>);</span>
        <span class=n>message</span><span class=o>.</span><span class=na>setFrom</span><span class=o>(</span><span class=k>new</span> <span class=n>InternetAddress</span><span class=o>(</span><span class=n>MAIL_FROM</span><span class=o>));</span>
        <span class=n>message</span><span class=o>.</span><span class=na>setRecipients</span><span class=o>(</span><span class=n>RecipientType</span><span class=o>.</span><span class=na>TO</span><span class=o>,</span> <span class=n>InternetAddress</span><span class=o>.</span><span class=na>parse</span><span class=o>(</span><span class=n>mailTo</span><span class=o>));</span>
        <span class=n>message</span><span class=o>.</span><span class=na>setRecipients</span><span class=o>(</span><span class=n>RecipientType</span><span class=o>.</span><span class=na>CC</span><span class=o>,</span> <span class=n>InternetAddress</span><span class=o>.</span><span class=na>parse</span><span class=o>(</span><span class=n>mailCc</span><span class=o>));</span>
        <span class=n>message</span><span class=o>.</span><span class=na>setSubject</span><span class=o>(</span><span class=n>subject</span><span class=o>);</span>
        <span class=n>message</span><span class=o>.</span><span class=na>setContent</span><span class=o>(</span><span class=n>content</span><span class=o>,</span> <span class=s>&#34;text/html;charset=UTF-8&#34;</span><span class=o>);</span>
        <span class=n>message</span><span class=o>.</span><span class=na>setSentDate</span><span class=o>(</span><span class=k>new</span> <span class=n>Date</span><span class=o>());</span>
        <span class=n>message</span><span class=o>.</span><span class=na>saveChanges</span><span class=o>();</span>

        <span class=k>return</span> <span class=n>message</span><span class=o>;</span>
    <span class=o>}</span>

    <span class=cm>/**
</span><span class=cm>     * create a mail with attachments
</span><span class=cm>     *
</span><span class=cm>     * @param session
</span><span class=cm>     * @param mailTo
</span><span class=cm>     * @param mailCc
</span><span class=cm>     * @param subject
</span><span class=cm>     * @param content
</span><span class=cm>     * @param attachments
</span><span class=cm>     * @return
</span><span class=cm>     */</span>
    <span class=kd>private</span> <span class=kd>static</span> <span class=n>MimeMessage</span> <span class=nf>createMail</span><span class=o>(</span><span class=kd>final</span> <span class=n>Session</span> <span class=n>session</span><span class=o>,</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>mailTo</span><span class=o>,</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>mailCc</span><span class=o>,</span>
            <span class=kd>final</span> <span class=n>String</span> <span class=n>subject</span><span class=o>,</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>content</span><span class=o>,</span> <span class=kd>final</span> <span class=n>String</span><span class=o>[]</span> <span class=n>attachments</span><span class=o>)</span> <span class=kd>throws</span> <span class=n>Exception</span> <span class=o>{</span>
        <span class=kd>final</span> <span class=n>MimeMessage</span> <span class=n>message</span> <span class=o>=</span> <span class=k>new</span> <span class=n>MimeMessage</span><span class=o>(</span><span class=n>session</span><span class=o>);</span>
        <span class=n>message</span><span class=o>.</span><span class=na>setFrom</span><span class=o>(</span><span class=k>new</span> <span class=n>InternetAddress</span><span class=o>(</span><span class=n>MAIL_FROM</span><span class=o>));</span>
        <span class=n>message</span><span class=o>.</span><span class=na>setRecipients</span><span class=o>(</span><span class=n>RecipientType</span><span class=o>.</span><span class=na>TO</span><span class=o>,</span> <span class=n>InternetAddress</span><span class=o>.</span><span class=na>parse</span><span class=o>(</span><span class=n>mailTo</span><span class=o>));</span>
        <span class=n>message</span><span class=o>.</span><span class=na>setRecipients</span><span class=o>(</span><span class=n>RecipientType</span><span class=o>.</span><span class=na>CC</span><span class=o>,</span> <span class=n>InternetAddress</span><span class=o>.</span><span class=na>parse</span><span class=o>(</span><span class=n>mailCc</span><span class=o>));</span>
        <span class=n>message</span><span class=o>.</span><span class=na>setSubject</span><span class=o>(</span><span class=n>subject</span><span class=o>);</span>
        <span class=c1>// set the multipart of the mail
</span><span class=c1></span>        <span class=kd>final</span> <span class=n>MimeMultipart</span> <span class=n>multipart</span> <span class=o>=</span> <span class=k>new</span> <span class=n>MimeMultipart</span><span class=o>();</span>
        <span class=c1>// set content part of the mail
</span><span class=c1></span>        <span class=kd>final</span> <span class=n>MimeBodyPart</span> <span class=n>contentPart</span> <span class=o>=</span> <span class=k>new</span> <span class=n>MimeBodyPart</span><span class=o>();</span>
        <span class=n>contentPart</span><span class=o>.</span><span class=na>setContent</span><span class=o>(</span><span class=n>content</span><span class=o>,</span> <span class=s>&#34;text/html;charset=UTF-8&#34;</span><span class=o>);</span>
        <span class=n>multipart</span><span class=o>.</span><span class=na>addBodyPart</span><span class=o>(</span><span class=n>contentPart</span><span class=o>);</span>
        <span class=c1>// set attachment part of the mail
</span><span class=c1></span>        <span class=kd>final</span> <span class=n>MimeBodyPart</span> <span class=n>attach1</span> <span class=o>=</span> <span class=k>new</span> <span class=n>MimeBodyPart</span><span class=o>();</span>
        <span class=kd>final</span> <span class=n>MimeBodyPart</span> <span class=n>attach2</span> <span class=o>=</span> <span class=k>new</span> <span class=n>MimeBodyPart</span><span class=o>();</span>
        <span class=k>if</span> <span class=o>(</span><span class=n>attachments</span> <span class=o>!=</span> <span class=kc>null</span> <span class=o>&amp;&amp;</span> <span class=n>attachments</span><span class=o>.</span><span class=na>length</span> <span class=o>!=</span> <span class=n>0</span><span class=o>)</span> <span class=o>{</span>
            <span class=kd>final</span> <span class=kt>int</span> <span class=n>length</span> <span class=o>=</span> <span class=n>attachments</span><span class=o>.</span><span class=na>length</span><span class=o>;</span>
            <span class=k>if</span> <span class=o>(</span><span class=n>length</span> <span class=o>==</span> <span class=n>1</span><span class=o>)</span> <span class=o>{</span>
                <span class=n>attach1</span><span class=o>.</span><span class=na>attachFile</span><span class=o>(</span><span class=n>attachments</span><span class=o>[</span><span class=n>0</span><span class=o>]);</span>
                <span class=n>multipart</span><span class=o>.</span><span class=na>addBodyPart</span><span class=o>(</span><span class=n>attach1</span><span class=o>);</span>
            <span class=o>}</span>
            <span class=k>if</span> <span class=o>(</span><span class=n>length</span> <span class=o>==</span> <span class=n>2</span><span class=o>)</span> <span class=o>{</span>
                <span class=n>attach1</span><span class=o>.</span><span class=na>attachFile</span><span class=o>(</span><span class=n>attachments</span><span class=o>[</span><span class=n>0</span><span class=o>]);</span>
                <span class=n>attach2</span><span class=o>.</span><span class=na>attachFile</span><span class=o>(</span><span class=n>attachments</span><span class=o>[</span><span class=n>1</span><span class=o>]);</span>
                <span class=n>multipart</span><span class=o>.</span><span class=na>addBodyPart</span><span class=o>(</span><span class=n>attach1</span><span class=o>);</span>
                <span class=n>multipart</span><span class=o>.</span><span class=na>addBodyPart</span><span class=o>(</span><span class=n>attach2</span><span class=o>);</span>
            <span class=o>}</span>
        <span class=o>}</span>
        <span class=n>message</span><span class=o>.</span><span class=na>setContent</span><span class=o>(</span><span class=n>multipart</span><span class=o>);</span>
        <span class=n>message</span><span class=o>.</span><span class=na>setSentDate</span><span class=o>(</span><span class=k>new</span> <span class=n>Date</span><span class=o>());</span>
        <span class=n>message</span><span class=o>.</span><span class=na>saveChanges</span><span class=o>();</span>

        <span class=k>return</span> <span class=n>message</span><span class=o>;</span>
    <span class=o>}</span>

    <span class=cm>/**
</span><span class=cm>     * get the session to transport mails
</span><span class=cm>     */</span>
    <span class=kd>private</span> <span class=kd>static</span> <span class=n>Session</span> <span class=nf>getSession</span><span class=o>()</span> <span class=o>{</span>
        <span class=c1>// set the properties for connecting the mail server
</span><span class=c1></span>        <span class=kd>final</span> <span class=n>Properties</span> <span class=n>props</span> <span class=o>=</span> <span class=k>new</span> <span class=n>Properties</span><span class=o>();</span>
        <span class=n>props</span><span class=o>.</span><span class=na>setProperty</span><span class=o>(</span><span class=s>&#34;mail.debug&#34;</span><span class=o>,</span> <span class=s>&#34;true&#34;</span><span class=o>);</span>
        <span class=n>props</span><span class=o>.</span><span class=na>setProperty</span><span class=o>(</span><span class=s>&#34;mail.transport.protocol&#34;</span><span class=o>,</span> <span class=s>&#34;smtp&#34;</span><span class=o>);</span>
        <span class=n>props</span><span class=o>.</span><span class=na>setProperty</span><span class=o>(</span><span class=s>&#34;mail.host&#34;</span><span class=o>,</span> <span class=n>SMTP_HOST</span><span class=o>);</span>
        <span class=n>props</span><span class=o>.</span><span class=na>setProperty</span><span class=o>(</span><span class=s>&#34;mail.smtp.auth&#34;</span><span class=o>,</span> <span class=s>&#34;true&#34;</span><span class=o>);</span>
        <span class=n>props</span><span class=o>.</span><span class=na>setProperty</span><span class=o>(</span><span class=s>&#34;mail.smtp.port&#34;</span><span class=o>,</span> <span class=n>SMTP_PORT</span><span class=o>);</span>
        <span class=c1>// ssl
</span><span class=c1></span>        <span class=n>props</span><span class=o>.</span><span class=na>setProperty</span><span class=o>(</span><span class=s>&#34;mail.imap.ssl.enable&#34;</span><span class=o>,</span> <span class=s>&#34;true&#34;</span><span class=o>);</span>
        <span class=n>props</span><span class=o>.</span><span class=na>setProperty</span><span class=o>(</span><span class=s>&#34;mail.imap.ssl.socketFactory.class&#34;</span><span class=o>,</span> <span class=s>&#34;DummySSLSocketFactory&#34;</span><span class=o>);</span>
        <span class=n>props</span><span class=o>.</span><span class=na>setProperty</span><span class=o>(</span><span class=s>&#34;mail.imap.ssl.socketFactory.fallback&#34;</span><span class=o>,</span> <span class=s>&#34;false&#34;</span><span class=o>);</span>
        <span class=c1>// create the session
</span><span class=c1></span>        <span class=kd>final</span> <span class=n>Session</span> <span class=n>session</span> <span class=o>=</span> <span class=n>Session</span><span class=o>.</span><span class=na>getDefaultInstance</span><span class=o>(</span><span class=n>props</span><span class=o>);</span>

        <span class=k>return</span> <span class=n>session</span><span class=o>;</span>
    <span class=o>}</span>

<span class=o>}</span>
</code></pre></td></tr></table></div></div><p>以上的工具类有个进行了重载的方法，因为对于没有附件的邮件和有附件的邮件，在构造邮件对象时是不一样的，有附件的邮件会稍微复杂一点。接着是测试类。</p><div class=highlight><div class=chroma><table class=lntable><tr><td class=lntd><pre class=chroma><code><span class=lnt> 1
</span><span class=lnt> 2
</span><span class=lnt> 3
</span><span class=lnt> 4
</span><span class=lnt> 5
</span><span class=lnt> 6
</span><span class=lnt> 7
</span><span class=lnt> 8
</span><span class=lnt> 9
</span><span class=lnt>10
</span><span class=lnt>11
</span><span class=lnt>12
</span><span class=lnt>13
</span><span class=lnt>14
</span><span class=lnt>15
</span><span class=lnt>16
</span><span class=lnt>17
</span><span class=lnt>18
</span><span class=lnt>19
</span><span class=lnt>20
</span><span class=lnt>21
</span><span class=lnt>22
</span><span class=lnt>23
</span></code></pre></td><td class=lntd><pre class=chroma><code class=language-java data-lang=java><span class=kd>public</span> <span class=kd>class</span> <span class=nc>Test</span> <span class=o>{</span>
	<span class=c1>//收件人，多人的话要用英文的&#34;,&#34;来隔开
</span><span class=c1></span>    <span class=kd>private</span> <span class=kd>static</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>MAIL_TO</span> <span class=o>=</span> <span class=s>&#34;XXX@qq.com&#34;</span><span class=o>;</span>
    <span class=c1>//抄送人，多人的话要用英文的&#34;,&#34;来隔开
</span><span class=c1></span>    <span class=kd>private</span> <span class=kd>static</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>MAIL_CC</span> <span class=o>=</span> <span class=s>&#34;XXX@qq.com&#34;</span><span class=o>;</span>
    <span class=c1>//邮件的主题（因为只是测试用，所以写成静态常量了）
</span><span class=c1></span>    <span class=kd>private</span> <span class=kd>static</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>SUBJECT</span> <span class=o>=</span> <span class=s>&#34;It&#39;s a test mail&#34;</span><span class=o>;</span>
    <span class=c1>//邮件的内容（因为只是测试用，所以写成静态常量了）
</span><span class=c1></span>    <span class=kd>private</span> <span class=kd>static</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>CONTENT</span> <span class=o>=</span> <span class=s>&#34;Hello World!&lt;br&gt;Bye!&#34;</span><span class=o>;</span>
    <span class=kd>private</span> <span class=kd>static</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>FILE_1</span> <span class=o>=</span> <span class=s>&#34;附件1的路径&#34;</span><span class=o>;</span>
    <span class=kd>private</span> <span class=kd>static</span> <span class=kd>final</span> <span class=n>String</span> <span class=n>FILE_2</span> <span class=o>=</span> <span class=s>&#34;附件2的路径&#34;</span><span class=o>;</span>

    <span class=kd>public</span> <span class=kd>static</span> <span class=kt>void</span> <span class=nf>main</span><span class=o>(</span><span class=kd>final</span> <span class=n>String</span><span class=o>[]</span> <span class=n>args</span><span class=o>)</span> <span class=o>{</span>
        <span class=kd>final</span> <span class=n>String</span><span class=o>[]</span> <span class=n>attachments</span> <span class=o>=</span> <span class=o>{};</span>
<span class=c1>//        final String[] attachments = {FILE_1, FILE_2};
</span><span class=c1></span>        <span class=k>try</span> <span class=o>{</span>
<span class=c1>//            JavaMailUtils.sendMail(MAIL_TO, MAIL_CC, SUBJECT, CONTENT);
</span><span class=c1></span>            <span class=n>JavaMailUtils</span><span class=o>.</span><span class=na>sendMail</span><span class=o>(</span><span class=n>MAIL_TO</span><span class=o>,</span> <span class=n>MAIL_CC</span><span class=o>,</span> <span class=n>SUBJECT</span><span class=o>,</span> <span class=n>CONTENT</span><span class=o>,</span> <span class=n>attachments</span><span class=o>);</span>
        <span class=o>}</span> <span class=k>catch</span> <span class=o>(</span><span class=kd>final</span> <span class=n>Exception</span> <span class=n>e</span><span class=o>)</span> <span class=o>{</span>
            <span class=n>e</span><span class=o>.</span><span class=na>printStackTrace</span><span class=o>();</span>
        <span class=o>}</span>
    <span class=o>}</span>
<span class=o>}</span>
</code></pre></td></tr></table></div></div><p>最后是导入的jar包：</p><p><a href=http://download.csdn.net/download/lewky_liu/10129340 target=_blank rel="noopener noreffer">javax.mail-1.6.0.jar</a></p><h2 id=补充>补充</h2><p>JavaMail提供了多个属性，这些属性的值都必须是字符串，否则设置无效，如下：</p><ul><li><code>mail.smtp.sendpartial</code>设置为<code>"true"</code>，当一次发送多个地址时就不会因为某个地址无效而全部发送失败。</li><li><code>mail.smtp.auth</code>设置为<code>"false"</code>时，则无需验证账号密码即可发送邮件。SMTP只是个简单的邮件发送协议，如果不设置校验，可能会造成垃圾邮件泛滥的问题。不过我发现公司项目在发送邮件时并没有设置验证，可能是图方便。</li></ul><h2 id=参考链接>参考链接</h2><ul><li><a href="http://www.mytju.com/classCode/news_readNews.asp?newsID=231" target=_blank rel="noopener noreffer">[疑问]JavaMail的mail.smtp.sendpartial不起作用？</a></li></ul><div class="details admonition warning open"><div class="details-summary admonition-title"><i class="icon fas fa-exclamation-triangle fa-fwwarning"></i>警告<i class="details-icon fas fa-angle-right fa-fw"></i></div><div class=details-content><div class=admonition-content>本文最后更新于 <span class=timeago datetime=2021-03-17T23:31:05 title="March 17, 2021">March 17, 2021</span>，文中内容可能已过时，请谨慎使用。</div></div></div><div class=post-reward><input type=checkbox name=reward id=reward hidden>
<label class=reward-button for=reward>赞赏支持</label><div class=qr-code><label class=qr-code-image for=reward><img class=image src=https://cdn.jsdelivr.net/gh/lewky/lewky.github.io@master/images/common/wechat.png>
<span>微信打赏</span></label>
<label class=qr-code-image for=reward><img class=image src=https://cdn.jsdelivr.net/gh/lewky/lewky.github.io@master/images/common/alipay.png>
<span>支付宝打赏</span></label></div></div></div><div class=post-footer id=post-footer><div class=post-info><div class=post-info-line><div class=post-info-mod><span>更新于 2021-03-17</span></div><div class=post-info-license><span><a rel="license external nofollow noopener noreffer" href=https://creativecommons.org/licenses/by-nc/4.0/ target=_blank>CC BY-NC 4.0</a></span></div></div><div class=post-info-line><div class=post-info-md><span><a class=link-to-markdown href=/posts/javamail.html/index.md target=_blank>阅读原始文档</a></span></div><div class=post-info-share><span><a href=javascript:void(0); title="分享到 Twitter" data-sharer=twitter data-url=https://lewky.cn/posts/javamail.html/ data-title=JavaMail-发送一封简单邮件（附带附件） data-hashtags=工作记录><i class="fab fa-twitter fa-fw"></i></a><a href=javascript:void(0); title="分享到 Facebook" data-sharer=facebook data-url=https://lewky.cn/posts/javamail.html/ data-hashtag=工作记录><i class="fab fa-facebook-square fa-fw"></i></a><a href=javascript:void(0); title="分享到 Hacker News" data-sharer=hackernews data-url=https://lewky.cn/posts/javamail.html/ data-title=JavaMail-发送一封简单邮件（附带附件）><i class="fab fa-hacker-news fa-fw"></i></a><a href=javascript:void(0); title="分享到 Line" data-sharer=line data-url=https://lewky.cn/posts/javamail.html/ data-title=JavaMail-发送一封简单邮件（附带附件）><i data-svg-src=https://cdn.jsdelivr.net/npm/simple-icons@2.14.0/icons/line.svg></i></a><a href=javascript:void(0); title="分享到 微博" data-sharer=weibo data-url=https://lewky.cn/posts/javamail.html/ data-title=JavaMail-发送一封简单邮件（附带附件）><i class="fab fa-weibo fa-fw"></i></a></span></div></div></div><div class=post-info-more><section class=post-tags><i class="fas fa-tags fa-fw"></i>&nbsp;<a href=/tags/%E5%B7%A5%E4%BD%9C%E8%AE%B0%E5%BD%95/>工作记录</a></section><section><span><a href=javascript:void(0); onclick=window.history.back();>返回</a></span>&nbsp;|&nbsp;<span><a href=/>主页</a></span></section></div><div class=post-nav><a href=/posts/39f5b6b2.html/ class=prev rel=prev title="cmd - 如何在bat文件中调用另一个bat文件"><i class="fas fa-angle-left fa-fw"></i>cmd - 如何在bat文件中调用另一个bat文件</a>
<a href=/posts/90196397.html/ class=next rel=next title=PostgreSQL笔记-查看表的主外键等约束关系>PostgreSQL笔记-查看表的主外键等约束关系<i class="fas fa-angle-right fa-fw"></i></a></div></div><div id=comments><div id=waline></div><script src=https://cdn.jsdelivr.net/npm/@waline/client/dist/Waline.min.js></script><script>new Waline({el:'#waline',meta:["nick","mail","link"],requiredMeta:["nick","mail"],login:"force",placeholder:"为防恶意灌水攻击，评论前需注册并登录，望见谅~",serverURL:"https://comment.lewky.cn/",avatarCDN:"https://sdn.geekzu.org/avatar/",pageSize:20,avatar:"retro",lang:"zh-CN",visitor:true,highlight:true,uploadImage:false,emoji:['https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/嘉然今天吃什么','https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/大航海嘉然','https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/向晚大魔王','https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/贝拉kira','https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/珈乐Carol','https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/乃琳Queen','https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/EveOneCat','https://cdn.jsdelivr.net/gh/walinejs/emojis@1.0.0/weibo','https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/滑稽','https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/default']});</script></div></article></div></main><footer class=footer><div class=footer-container><div class=footer-line><span id=run-time></span>|
<a href=http://rssblog.vercel.app/ target=_blank rel=noopener title=RSSBlog><i class="fas fa-fw fa-inbox"></i>&nbsp;RSSBlog</a></div><div class=footer-line><i class="far fa-copyright fa-fw"></i><span itemprop=copyrightYear>2018 - 2022</span><span class=author itemprop=copyrightHolder>&nbsp;<a href=/ target=_blank>雨临Lewis</a></span>&nbsp;|&nbsp;<span class=license><a rel="license external nofollow noopener noreffer" href=https://creativecommons.org/licenses/by-nc/4.0/ target=_blank>CC BY-NC 4.0</a></span><span class=icp-splitter>&nbsp;|&nbsp;</span><br class=icp-br><span class=icp><a target=_blank href=http://www.beian.miit.gov.cn/ style=font-weight:700>粤ICP备19103822</a></span></div></div></footer></div><div id=fixed-buttons><a href=# id=back-to-top class=fixed-button title=回到顶部><i class="fas fa-arrow-up fa-fw"></i></a><a href=# id=view-comments class=fixed-button title=查看评论><i class="fas fa-comment fa-fw"></i></a></div><div class=sidebar_wo><div id=leimu><img src=https://cdn.jsdelivr.net/gh/lewky/lewky.github.io@master/images/b2t/leimuA.png alt=雷姆 onmouseover="this.src='https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/b2t/leimuB.png'" onmouseout="this.src='https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/b2t/leimuA.png'" title=回到顶部></div><div class=sidebar_wo id=lamu><img src=https://cdn.jsdelivr.net/gh/lewky/lewky.github.io@master/images/b2t/lamuA.png alt=雷姆 onmouseover="this.src='https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/b2t/lamuB.png'" onmouseout="this.src='https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/b2t/lamuA.png'" title=回到底部></div></div><link rel=stylesheet href=https://cdn.jsdelivr.net/npm/lightgallery.js@1.2.0/dist/css/lightgallery.min.css><script type=text/javascript src=https://cdn.jsdelivr.net/npm/smooth-scroll@16.1.3/dist/smooth-scroll.min.js></script><script type=text/javascript src=https://cdn.jsdelivr.net/npm/lazysizes@5.2.2/lazysizes.min.js></script><script type=text/javascript src=https://cdn.jsdelivr.net/npm/lightgallery.js@1.2.0/dist/js/lightgallery.min.js></script><script type=text/javascript src=https://cdn.jsdelivr.net/npm/lg-thumbnail.js@1.2.0/dist/lg-thumbnail.min.js></script><script type=text/javascript src=https://cdn.jsdelivr.net/npm/lg-zoom.js@1.2.0/dist/lg-zoom.min.js></script><script type=text/javascript src=https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js></script><script type=text/javascript src=https://cdn.jsdelivr.net/npm/sharer.js@0.4.0/sharer.min.js></script><script type=text/javascript>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":30},"comment":{},"lightGallery":{"actualSize":false,"exThumbImage":"data-thumbnail","hideBarsDelay":2000,"selector":".lightgallery","speed":400,"thumbContHeight":80,"thumbWidth":80,"thumbnail":true}};</script><script type=text/javascript src=/js/theme.min.js></script><script type=text/javascript src=https://cdn.jsdelivr.net/npm/jquery@2.1.3/dist/jquery.min.js></script><script type=text/javascript src=https://cdn.jsdelivr.net/npm/jquery-backstretch@2.1.18/jquery.backstretch.min.js></script><script>var $cdnPrefix="https://cdn.jsdelivr.net/gh/lewky/lewky.github.io@master";</script><script type=text/javascript src=/js/custom.js></script><script>var _hmt=_hmt||[];(function(){var hm=document.createElement("script");hm.src="https://hm.baidu.com/hm.js?6f278ed0fdb01edb3b1e7398379e5432";var s=document.getElementsByTagName("script")[0];s.parentNode.insertBefore(hm,s);})();</script></body></html>